package com.xtedu.examproject.util;

import com.xtedu.examproject.entity.Menu;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MenuTreeBuilder {
    public static List<Menu> buildMenuTree(List<Menu> menus) {
        //pid 不为0的Menu 按pid分组
        Map<Integer, List<Menu>> map = menus.stream().filter(m -> m.getPid() != 0).collect(Collectors.groupingBy(Menu::getPid));
        //遍历List 如果map中有key与List的元素的id一致则将其放入children集合
        menus.forEach(m -> {
            if (map.containsKey(m.getId())) {
                m.setChildren(map.get(m.getId()));
            }
        });
        //返回第一级Menu
        return menus.stream().filter(m -> m.getPid() == 0).toList();
    }
}
